
package nl.rainbowsheep.reisorg.rest.service.controller;

import java.util.List;
import nl.rainbowsheep.reisorg.rest.service.model.Country;
import nl.rainbowsheep.reisorg.rest.service.service.CountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.acls.model.NotFoundException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * Controller class for Country where Country objects are validated
 */
@RestController
@RequestMapping("/country")
public class CountryController {

    @Autowired
    private CountryService countryService;

    /**
     * Method to get a json serialized Country object.
     *
     * @param name Name of the country
     * @return the saved country object
     * @throws NotFoundException when country with given name can't be found
     */
    @RequestMapping(value = "/getbyname", method = RequestMethod.GET)
    public Country getCountryByName(@RequestParam(value = "name", required = true) String name) throws NotFoundException {
        Country country = countryService.getCountryByName(name);
        if (country != null) {
            return country;
        } else {
            throw new NotFoundException(name);
        }
    }

    @RequestMapping(value = "/getall", method = RequestMethod.GET)
    @ResponseBody
    public List<Country> getAllCountries() throws Exception {
        List<Country> countries = countryService.getAllCountries();
        return countries;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Country saveCountry(@RequestBody Country country) throws Exception {
        //Why exacly are we catching a thrown specific exception only to throw a generic exception???
        try {
            return countryService.save(country);
        } catch (Exception ex) {
            throw new Exception();
        }
    }
}
